﻿using System.Globalization;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	public static class ModelBindingContextExtensions
	{
		public static T GetValueOrDefault<T>(this ModelBindingContext bindingContext, string key)
		{
			return bindingContext.GetValueOrDefault(key, default(T));
		}

		public static T GetValueOrDefault<T>(this ModelBindingContext bindingContext, string key, T defaultValue)
		{
			Guard.NotNullOrEmpty(key, "key");

			var valueResult = bindingContext.GetValueResult(key);

			if (valueResult == null)
			{
				return defaultValue;
			}

			try
			{
				return (T)valueResult.ConvertTo(typeof (T), CultureInfo.CurrentUICulture);
			}
			catch
			{
				bindingContext.ModelState.AddModelError(key, "{0} is not a valid format for {1}.", valueResult.AttemptedValue, typeof (T).Name);

				return default(T);
			}
		}

		private static ValueProviderResult GetValueResult(this ModelBindingContext bindingContext, string key)
		{
			Guard.NotNullOrEmpty(key, "key");

			// Try it with the prefix.
			var valueResult = bindingContext.ValueProvider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, key));

			// Didn't work? Try without the prefix if needed.
			if (valueResult == null
			    && bindingContext.FallbackToEmptyPrefix)
			{
				valueResult = bindingContext.ValueProvider.GetValue(key);
			}

			return valueResult;
		}
	}
}